package com.wanyangproject.androidlearning.multiThread.energyConservation;


/*
 * 能量守恒定律：能量盒子里能量总数不会改变，只会从一个盒子转移到另一个盒子
 *
 *
 * */
public class Energy {


    private double[] boxes;
    private Object object = new Object();

    public Energy(int num) {
        this.boxes = new double[num];
        for (int i = 0; i < 1000; i++) {
            boxes[i] = 100;
        }
    }

    public void transfer(int from, int to, double amount) {
        if (boxes[from] < amount) {
            return;
        }
        synchronized (object){
            while (boxes[from] < amount){
                try {
                    object.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(String.format("能量%f从盒子%d转移到盒子%d，线程%s。能量总数为%f",amount,from,to,Thread.currentThread().getName(),sum()));
            double froma = boxes[from];
            double toa = boxes[to];
            boxes[from] -= amount;
            boxes[to] += amount;
            System.out.println(String.format("转出盒子%d原有%f,现有%f;转进盒子%d原有%f,现有%f",from,froma,boxes[from],to,toa,boxes[to]));
            object.notifyAll();
        }
    }

    public double sum() {
        double sum = 0;
        for (int i=0;i<boxes.length;i++){
            sum += boxes[i];
//            System.out.println(String.format("第%d个盒子的能量是%d",i,boxes[i]));
        }
        return sum;
    }

    public int getBoxNum(){
        return boxes.length;
    }

}
